package com.fenghongzhang.sample.listview

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.Toast
import com.fenghongzhang.sample.Food
import com.fenghongzhang.sample.R
import kotlinx.android.synthetic.main.activity_sample_list_view.*

/**
 * listView 用kt的写法
 */
class SampleListViewActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sample_list_view)

        //数据源 mutableListOf是可以添加的list集合 listOf是固定长度的list结合
        val list = mutableListOf<Food>()
        for (i in 0..20){
            list.add(Food("苹果",R.mipmap.ic_launcher_round))
            if(i % 3 == 0){
                list.add(Food("苹果",null))
            }
        }

        //实例化适配器
        val adapter = FoodListViewAdapter(this,R.layout.list_view_layout,list)

        //设置适配器
        listView.adapter = adapter

        //点击
        listView.setOnItemClickListener{ _, _, position, _ ->
            val food = list[position]
            Toast.makeText(this,food.name,Toast.LENGTH_LONG).show()
        }

        //长按
        listView.setOnItemLongClickListener{ _, _, i,_ ->
            val food = list[i]
            Toast.makeText(this,food.name,Toast.LENGTH_LONG).show()
            //是否拦截
            false
        }
    }

    /**
     * companion object 相当于静态static .如果让java 也可调用可以加注解@jvmStatic
     */
    companion object {
        @JvmStatic
        fun launch(context:Context){
            val intent = Intent(context, SampleListViewActivity::class.java)
            context.startActivity(intent)
        }
    }
}
